package com.ckjava.config;

import com.ckjava.entity.DbEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 通过 ThreadLocal 来存储当前线程的 数据库 key 变量
 */
public class MultiDataSourceHolder {

    private static final Logger logger = LoggerFactory.getLogger(MultiDataSourceHolder.class);

    /**
     * 通过 ThreadLocal 来存储当前线程的 dataSource key
     */
    private static final ThreadLocal<DbEnum> contextHolder = new ThreadLocal<>();

    public static void setDataSource(DbEnum dataSource) {
        logger.info("Thread {} set datasource {}", Thread.currentThread().getName(), dataSource);
        contextHolder.set(dataSource);
    }

    public static DbEnum getDataSource() {
        return contextHolder.get();
    }

    public static void clearDataSource() {
        logger.info("Thread {} unset datasource {}", Thread.currentThread().getName(), contextHolder.get());
        contextHolder.remove();
    }
}
